package com.bamboo.framework.framework.security.service.impl;

import com.bamboo.framework.framework.security.entity.UserRole;
import com.bamboo.framework.framework.security.mapper.UserRoleMapper;
import com.bamboo.framework.framework.security.service.IUserRoleService;
import com.bamboo.framework.common.format.ReturnMsg;
import com.bamboo.framework.common.enums.Status;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.List;
import java.util.Map;
import jodd.util.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 郭晴
 * @since 2018-12-15
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements
    IUserRoleService {

  @Override
  @Transactional(rollbackFor = Exception.class)
  public ReturnMsg saveUserRole(Map<String, Object> map) {
    Integer userId = StringUtil.isEmpty(map.get("userId").toString())?0: Integer.valueOf(map.get("userId").toString());
    List<Integer> roleIds = (List<Integer>) map.get("roleIds");
    if (userId == null || userId < 1) {
      return new ReturnMsg(Status.PARAMETER_NULL, "参数userId不存在");
    }
    if (roleIds == null) {
      return new ReturnMsg(Status.PARAMETER_NULL, "参数roleIds不存在");
    }

    boolean dele = this.remove(new QueryWrapper<UserRole>().eq("userId", userId));
    if (!dele) {
      return new ReturnMsg(Status.ERROR, "保存失败");
    }
    for (Integer roleId : roleIds) {
      UserRole userRole = new UserRole();
      userRole.setUserId(userId);
      userRole.setRoleId(roleId);
      this.save(userRole);
    }
    return new ReturnMsg(Status.SUCCESS);

  }
}
